package com.xrit.sunnyday.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.pojo.Permission;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.pojo.UserInfo;
import com.xrit.sunnyday.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 类名称: UserServiceImpl
 * 类描述:TODO
 * 创建人: czb
 * 创建时间:2022/7/6 上午 09:43
 * Version 1.0.0
 */
@Component("userSecurity")
public class UserSecurity implements UserDetailsService {
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userService.findByUserName(username);
        if (null != userInfo) {
            List<GrantedAuthority> list = new ArrayList<>();
            if (null != userInfo.getRoles()) {
                for (Role role : userInfo.getRoles()) {
                    list.add(new SimpleGrantedAuthority(role.getKeyword()));
                    if (null != role.getPermissions()) {
                        for (Permission permission : role.getPermissions()) {
                            list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                        }
                    }
                }
            }
            return new User(username, userInfo.getPassword(), list);
        }
        return null;
    }

}
